﻿#region Header

// // <copyright file="UnifyConfigurator.cs">
// // Copyright (c) 2013, Nicolas Anderlini
// // All rights reserved.
// // 
// // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// // 
// //     - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// //     - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// //     - Neither the name of Nicolas Anderlini nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// // 
// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// // </copyright>
// // <author>Nicolas Anderlini</author>
// // <email>nicolas.anderlini@live.fr</email>
// // <date>07-30-2013</date>
// // <summary></summary>

#endregion

#region

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using Unify.Unity.Internal;

#endregion

namespace Unify.Unity
{
    /// <summary>
    ///     Unify configurator for Unity
    /// </summary>
    public class UnifyConfigurator : IUnifyConfigurator
    {
        /// <summary>
        ///     Lifetime Selector provide methods to find the right LifeTimeManager
        /// </summary>
        private LifetimeSelector _lifetimeSelector;

        /// <summary>
        /// </summary>
        private UnifyComponents _unifyComponents;

        /// <summary>
        ///     Ctor
        /// </summary>
        public UnifyConfigurator()
        {
            IsConfigured = false;
        }

        /// <summary>
        ///     Return true if unify is correctly configured
        /// </summary>
        public bool IsConfigured { get; private set; }

        /// <summary>
        ///     Configure Unify with custom configuration section name
        /// </summary>
        /// <param name="configurationSectionName">Custom configuration section name</param>
        public IUnifyConfigurator Configure(IUnifyConfiguration configuration)
        {
            _unifyComponents = new UnifyComponents(configuration);

            _lifetimeSelector = new LifetimeSelector(_unifyComponents);
            //ok, configuration is done
            IsConfigured = true;
            return this;
        }

        /// <summary>
        ///     Configure the Unity container
        /// </summary>
        /// <param name="container">Container must be an implementation of IUnityContainer</param>
        public IUnifyConfigurator ConfigureContainer(object container)
        {
            var containerCast = container as IUnityContainer;

            //assert container is a IUnityContainer
            if (null == containerCast)
                throw new BadContainerTypeException("Container is not an IUnityContainer implementation");

            //check if unify is ready to operate
            if (!IsConfigured)
            {
                throw new UnifyConfigurationException("Unify is not properly configured.");
            }

            IDictionary<Type, UnifyContract> contracts = _unifyComponents.GetUnifyComponents();
            //register types in unity container
            foreach (var contract in contracts)
            {
                foreach (var abstraction in contract.Value.Interfaces)
                {
                    var lt = _lifetimeSelector.GetLifetimeManagerFromName(contract.Value.Lifetime);
                    containerCast.RegisterType(abstraction,
                                               contract.Key,
                                               lt,
                                               GetInjectionMemberArray(contract.Key, contract.Value));
                }
            }

            return this;
        }

        /// <summary>
        ///     Convert a type contract to list of InjectionMember unity type
        /// </summary>
        /// <param name="type"></param>
        /// <param name="unifyContract"></param>
        /// <returns></returns>
        private InjectionMember[] GetInjectionMemberArray(Type type, UnifyContract unifyContract)
        {
            //todo assure covariance works
            return unifyContract.PropertiesNameToInject.Select(p => new InjectionProperty(p)).ToArray();
        }
    }
}